<?php

/**
 * @author dao thanh son
 * @copyright 2010
 */
include_once("solrAPI/Service.php");
include_once("solrAPI/Document.php");
include_once("solrAPI/Response.php");
require_once("log4php/Logger.php");
require_once('config.php');

Logger::configure('log4php.properties');

function getMicrotime()
{
	$mtime = explode (' ',microtime());
	return (double) $mtime[0] + $mtime[1];
}

function getTimeTaken($endTime, $startTime)
{
	return number_format(($endTime - $startTime),4);
}

function getDeleteId($dbconn, $loggerContext){
	$query = "SELECT id FROM so_products_product_temp WHERE action = 0";
	$result = mysql_query($query, $dbconn);
	$limit = mysql_num_rows($result);
	//logger
	$loggerContext->info("Count of deleted products :". $limit);
	if($limit > 0 ){
		$queryDelete = "DELETE FROM so_products_product_temp WHERE action = 0 ORDER BY action_time LIMIT ".$limit;
		mysql_query($queryDelete, $dbconn);

		$arr_ID = array();
		while($rec=mysql_fetch_row($result)) {
			array_push($arr_ID, $rec[0]);
		}
		return  $arr_ID;
	} else {
		return false;
	}
}

function getUpdateRecord($dbconn, $loggerContext)
{
	$numQuery = "SELECT id FROM so_products_product_temp WHERE action = 1 OR action = 2";
	$numResult = mysql_query($numQuery, $dbconn);
	$numCount = mysql_num_rows($numResult);
	//logger
	$loggerContext->info("Count of Updated/Inserted products :". $numCount);
	if($numCount > 0)
	{
		$queryDelete = "DELETE FROM so_products_product_temp WHERE action = 1 OR action = 2 ORDER BY action_time LIMIT ". $numCount;
		mysql_query($queryDelete, $dbconn);

		$arr_update_ID = array();
		while($rec=mysql_fetch_row($numResult))
		{
			array_push($arr_update_ID, $rec[0]);
		}

		$strArrayUpdateID =  implode(",", $arr_update_ID);
		$query = "SELECT * FROM so_products_product WHERE id IN (" . $strArrayUpdateID  .")";
		$result = mysql_query($query, $dbconn);
		return $result;
	} else {
		return false;
	}
}

//date_default_timezone_set('Asia/Bangkok');
$start_code = getMicrotime();
//Intial Logger context
$logger = Logger::getLogger("Solr_Update_soProducts_product");

$dbServer_Conn = mysql_connect(DB_MASTER_SERVER ,DB_MASTER_USER ,DB_MASTER_PASSWORD);
if (!$dbServer_Conn) {
	$logger->error('Could not connect: ' . mysql_error($dbServer_Conn));
    die('Could not connect: ');
}
mysql_query ("SET NAMES 'UTF8'",$dbServer_Conn);

$db_selected = mysql_select_db(DB_MASTER_NAME,$dbServer_Conn);
if(!$db_selected) {
	$logger->error('Non DB exist'. mysql_error($dbServer_Conn));
	die('Non DB exist');
}

$solr = new Apache_Solr_Service(SOLR_SERVER , SOLR_PORT , SOLR_PATH_PRODUCTS);
if ($solr->ping())
{
	$start_getdeleteID_function = getMicrotime();
	$arraydeleteID = getDeleteId($dbServer_Conn, $logger);
	$end_getdeleteID_function = getMicrotime();

	$start_getUpdateRecord_function = getMicrotime();
	$arrproductUpdate = getUpdateRecord($dbServer_Conn, $logger);
	$end_getUpdateRecord_function = getMicrotime();

	$start_update_solr = getMicrotime();

	if($arraydeleteID != false) {
		$solr->deleteByMultipleIds($arraydeleteID);
	}

	if($arrproductUpdate != false){

		while ($row = mysql_fetch_object($arrproductUpdate)){

			$document = new Apache_Solr_Document();
			$document->addField( 'id' , $row->id);
			$document->addField( 'sku' , $row->sku);
			$document->addField( 'category_id' , $row->category_id);
			$document->addField( 'category_name' , $row->category_name);
			$document->addField( 'parent_id' , $row->parent_id);
			$document->addField( 'name' , $row->name);
			$document->addField( 'min_price' , $row->min_price);
			$document->addField( 'max_price' , $row->max_price);
			$document->addField( 'price' ,  is_null($row->price)? 0 : $row->price);
			$document->addField( 'quantity' , $row->quantity);
			$document->addField( 'description' , $row->description);
			echo "<br/> description :". $row->description;
			$document->addField( 'fulltext' , $row->fulltext);
			$document->addField( 'images' , $row->images);
			$document->addField( 'images_other' , $row->images_other);
			$document->addField( 'extra_fields' , $row->extra_fields);
			$document->addField( 'extra_fields_search' ,$row->extra_fields_search );
			$document->addField( 'published'  ,  $row->published);
			$document->addField( 'ordering' ,  $row->ordering);
			$document->addField( 'date' , $row->date);

			$document->addField( 'fullname' , $row->fullname);
			$document->addField( 'user_min_price' , $row->user_min_price);
			$document->addField( 'user_max_price' ,$row->user_max_price);
			$document->addField( 'price_old' , is_null($row->price_old)? 0 : $row->price_old);
			$document->addField( 'currency' , $row->currency);
			$document->addField( 'product_interest' , $row->product_interest);
			$document->addField( 'product_attach' , $row->product_attach);
			$document->addField( 'created_by_user' , $row->created_by_user);
			$document->addField( 'created_by_user_name' , $row->created_by_user_name);
			$document->addField( 'modify_by_user' , $row->modify_by_user);
			$document->addField( 'modify_by_user_name' ,  $row->modify_by_user_name);
			$document->addField( 'publish_up' , $row->publish_up);
			$document->addField( 'publish_down' ,  $row->publish_down);
			$document->addField( 'total_new_comment' , $row->total_new_comment);
			$document->addField( 'url_crawl' ,$row->url_crawl );

			$extra_fields = $row->extra_fields;
			if(isset($extra_fields)){
				$extraFieldArray = json_decode(utf8_encode($row->extra_fields));
				if(!is_null($extraFieldArray)){
					foreach($extraFieldArray as $extra_field){
						if (($extra_field->value != "") && ($extra_field->id != "")){
							if(is_array($extra_field->value)){
								$multiValFName = preg_replace("[fin|fis]", "fim", $extra_field->id);
								foreach($extra_field->value as $value){
									if($value != "" ) $document->addField($multiValFName, $value);
								}
							}
							else{
								$document->addField( $extra_field->id , $extra_field->value);
							}
						} else {
							$logger->warn("product-" .$row->id ."  ------- " . $extra_field->id . " ------- value is NULL" . "|| created by :" . $row->created_by_user_name . " | modify by :" . $row->modify_by_user_name );
						}
					}
				} else {
					$logger->warn("product-" .$row->id ."  ------- JSON can not parse extra_fields to object" . "|| created by :" . $row->created_by_user_name . " | modify by :" . $row->modify_by_user_name );
				}
				
			} else {
				$logger->warn("product-" .$row->id ."  ------- extra_fields is NULL" . "|| created by :" . $row->created_by_user_name . " | modify by :" . $row->modify_by_user_name );
			}
           
			try{
				$solr->addDocument($document);
			} catch (Exception $e){
				$logger->error('Can not update to Solr ----- productID-'. $row->id . $e->getMessage());
			}
		}
	}
    	
	try {
		$solr->commit();
	} catch (Exception $e) {
		$logger->error('Can not update to Solr' . $e->getMessage());
	}
	
	$end_update_solr = getMicrotime();
	
} else {
     $logger->error("error to connect Solr Server");
}

mysql_close($dbServer_Conn);
$end_code = getMicrotime();

$logger->info("Total time taken:" . getTimeTaken($end_code, $start_code) . " secs");
$logger->info("Get deleted product ID :" . getTimeTaken($end_getdeleteID_function, $start_getdeleteID_function) . " secs");
$logger->info("Get products Updated :" . getTimeTaken($end_getUpdateRecord_function, $start_getUpdateRecord_function) . " secs");
$logger->info("Update to Solr :". getTimeTaken($end_update_solr, $start_update_solr) . " secs");

?>